<template>
  <div class="search-suggestion">
    <van-cell v-for="(item, index) in suggestionData" :key="index" @click="onSearch(item)" icon="search">
      <div slot="title" v-html="lightHight(item, q)"></div>
    </van-cell>
  </div>
</template>

<script>
// 按需导入lodash 处理表单防抖
import { debounce } from 'lodash'
// 导入获取联想词接口请求
import { getSuggestion } from '@/api/search.js'
export default {
  name: 'SearchSuggestion',
  props: {
    // 接收父组件用户输入的值
    q: {
      type: String,
      require: true
    }
  },
  data () {
    return {
      suggestionData: []
    }
  },
  watch: {
    q: {
      immediate: true,
      handler: debounce(function (value) {
        this.loadSearchSuggestions(value)
      }, 300)
    }
  },
  methods: {
    // 定义获取联想词的请求
    async loadSearchSuggestions (q) {
      try {
        const { data } = await getSuggestion(q)
        this.suggestionData = data.data.options
      } catch (err) {
        this.$toast.fail('数据库信息异常，请稍后重试！')
      }
    },
    // 处理文字的高亮
    lightHight (sourceStr, keyword) {
      const reg = new RegExp(keyword, 'gi')
      const targetKeyword = `<span style="color: red">${keyword}</span>`
      return sourceStr.replace(reg, targetKeyword)
    },
    // 点击联想词搜索
    onSearch (item) {
      this.$emit('')
    }
  }
}
</script>

<style lang="less" scoped>

</style>
